package com.ocss.ocsscustomerserver.tools;


import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: lijiang
 * @Date: 2023-04-12 17:26
 * @Description: websocketRecorder
 */

@Component
public class WebsocketRecorder {

    //用于保存当前已经连接的ID
    private Map <String, WebSocketSession>  concurrentHashMap = new ConcurrentHashMap(10);

    //缓存Session对应的key
    private Map <WebSocketSession, String>  cacheSessionToKey = new ConcurrentHashMap(10);
    //根据ID移除session
    public WebSocketSession removeById (String id) {
        return  concurrentHashMap.remove(id) ;
    }


    //新加id-session
    public WebSocketSession putSession (String id, WebSocketSession session) {
        return concurrentHashMap.put(id, session);
    }

    //session断开时从表中移除
    public  WebSocketSession  getSession (String  id) {

        return concurrentHashMap.get(id);
    }

    public  String  getIdBySession (WebSocketSession session) {
        if (!concurrentHashMap.containsValue(session)) return  null;
        if (cacheSessionToKey.containsKey(session)) return  cacheSessionToKey.get(session);
        Set<String> get = concurrentHashMap.keySet();

        for (String key:get)
        {
            if (session == concurrentHashMap.get(key)) {
                cacheSessionToKey.put(session, key);
                return  key;
            }
        }
        return null;
    }

    public  void  removeBySession (WebSocketSession session) {
        Collection<WebSocketSession> collect = concurrentHashMap.values();
        if (collect.contains(session)) {
            collect.remove(session);
        }
        cacheSessionToKey.remove(session);

    }



    public  void  printAllSession () {
        System.out.println(concurrentHashMap);

    }

    public  int countSession () {
        return  concurrentHashMap.size();
    }


}
